#!/usr/local/bin/python

import os
import time
import codecs
import cgi
import cgitb; cgitb.enable()

reply = """Content-type: text/html

<html>
<head>
<title>MMLT Reader</title>
<style>
body{
	background-color: #FFFFFF;
	font-family: Myanmar3, verdana, aerial;
	font-size: small;
	color: #000000;
}
a{
	font-weight : bold;
	color: #0000FF;
}
a:visited{ color: #0000FF; }
a:hover{ color: #FF0000; }
.menu{
	background-color: #90EE90;
}
</style>
</head>
<body>
<h1>MMLT Reader 0.27</h1>
<p>Thanks for trying MMLT Reader 0.27.
The idea is to collect all recent Myanmar forum/blog posts (by RSS/Atom) and organize under one central place.
The posts are automatically classified under tags. The RSS/Atom feeds are downloaded at regular intervals.
Please visit <a href="http://www.mmgeeks.org/forum/viewtopic.php?f=83&t=945">Myanmar Geeks Forum</a> for discussions.</p>

<font color=#FF0000><b><center>Using Myanmar Unicode 5.1</center></b></font>
<table border=0>
<tr><td><b><font color=#FF0000>Latest feed refresh: %s.</font><b></td></tr>
</tr>
<tr>
	<td valign=top>
		<table border=0 class=menu>
			<tr><td><h4>Tags</h3>%s</td></tr>
			<tr><td><p>
				<form method=post action="http://reader.mmltlabs.org/reader.py">
				<b><font color=#FF0000>Submit a new tag</font></b>
				<input type=text name=newtag maxlength=32>
				<input type=submit value=Submit>
				</form>
			</p></td></tr>
			<tr><td><h4>Authors</h3>%s</td></tr>
		</table>
	</td>
	<td valign=top>%s%s</td>
</tr>
</table>

<form method=post action="http://reader.mmltlabs.org/reader.py">
<table>
<tr><td colspan=2><b><font color=#FF0000>Submit a new site</font></b></tr><td>
<tr><td>Site Title</td><td><input type=text name=newfeedtitle maxlength=64></td></tr>
<tr><td>Site RSS/Atom</td><td><input type=text name=newfeedurl maxlength=256></td></tr>
<tr><td><input type=submit value=Submit></td></tr>
</table>
</form>

<h3>Registered Sites</h3>
<ol>%s</ol>

<h3>Author Synonyms</h3>
<form method=post action="http://reader.mmltlabs.org/reader.py">
<table>
<tr><td colspan=2><b><font color=#FF0000>Submit another synonym</font></b></tr><td>
<tr><td>Author 1</td><td><input type=text name=authorsyn1 maxlength=64></td>
<td>Author 2</td><td><input type=text name=authorsyn2 maxlength=64></td>
<td><input type=submit value=Submit></td></tr>
</table>
</form>

<ol>%s</ol>
<h4>
<center>Myanmar Language Technology, 2009<br>
C Burglish Library by Soe Min (Mark)</center>
</h4>
</body>
</html>"""


def unistr_to_html(unistr):
	html = ''
	for ch in unistr:
		codenum = str(ord(ch))
		html += '&#%s' % codenum.zfill(4)
	return html

def html_to_unistr(html):
	return html.decode('utf-8')


if __name__ == '__main__':

	refresh = time.localtime(os.path.getmtime('feeds'))
	refresh_time = '%d/%d/%d %02d:%02d' % (refresh[2], refresh[1], refresh[0], refresh[3], refresh[4])

	bytags = {}
	for line in open('bytags.txt').readlines():
		line = line.strip('\n')
		tag, post_ids = line.split('\t')
		bytags[tag] = post_ids.split()
	tags_html = ''
	item_count = 0
	keys = bytags.keys()
	keys.sort()
	for tag in keys:
		tags_html += '<span><a href="http://reader.mmltlabs.org/reader.py?tag=%s">%s(%s)</a>&nbsp</span>' % (tag, tag, len(bytags[tag]))
		item_count += 1
		if item_count == 2:
			tags_html += '<br>'
			item_count = 0

	byauthor = {}
	for line in codecs.open('byauthor.txt', encoding='utf-8').readlines():
		line = line.strip('\n')
		author, post_ids = line.split('\t')
		byauthor[author] = post_ids.split()
	author_html = ''
	item_count = 0
	keys = byauthor.keys()
	keys.sort()
	for author in keys:
		author2 = unistr_to_html(author)
		author_html += '<span><a href="http://reader.mmltlabs.org/reader.py?author=%s">%s(%s)</a>&nbsp</span>' % (author2, author2, len(byauthor[author]))
		item_count += 1
		if item_count == 2:
			author_html += '<br>'
			item_count = 0

	posts = {}
	for line in codecs.open('posts.txt', encoding='utf-8').readlines():
		line = line.strip('\n')
		post_id, title, link, author = line.split('\t')
		posts[post_id] = [title, link, author]

	form = cgi.FieldStorage()

	msg_html = ''
	posts_html = ''
	tag = None
	author = None

	if form.has_key('newfeedurl'):
		newfeedurl = form.getvalue('newfeedurl')
		if form.has_key('newfeedtitle'):
			newfeedtitle = form.getvalue('newfeedtitle')
		else:
			newfeedtitle = 'Untitled'
		f = open('feedlist.txt', 'at')
		f.write('%s\t%s\n' % (newfeedtitle, newfeedurl))
		f.close()
		msg_html = 'Thank you for your submission. Your new feed will be read in the next 24 hours.'
	
	if form.has_key('authorsyn1') and form.has_key('authorsyn2'):
		authorsyn1 = html_to_unistr(form.getvalue('authorsyn1'))
		authorsyn2 = html_to_unistr(form.getvalue('authorsyn2'))
		f = codecs.open('synonyms.txt', 'a', encoding='utf-8')
		f.write('%s\t%s\n' % (authorsyn1, authorsyn2))
		f.close()
		msg_html = 'Thank you for your submission. Your author synonym pair will be read in the next 24 hours.'		

	elif form.has_key('newtag'):
		newtag = form.getvalue('newtag')
		f = open('tags.txt', 'at')
		f.write('%s\n' % newtag)
		f.close()
		msg_html = 'Thank you for your submission. Your new tag will be processed in the next 24 hours.'

	elif form.has_key('author'):
		user_author = html_to_unistr(form.getvalue('author'))
		if byauthor.has_key(user_author):
			author = user_author
			post_ids = byauthor[author]
			msg_html = '<b>AUTHOR - ' + unistr_to_html(author) + ':</b>'
		else:
			msg_html = 'The author you selected does not exist in our system. Please consider submitting his/her RSS/Atom feed.'

	elif form.has_key('tag'):
		user_tag = form.getvalue('tag')
		if bytags.has_key(user_tag):
			tag = user_tag
			post_ids = bytags[tag]
			msg_html = '<b>TAG - ' + tag + ':</b>'
		else:
			msg_html = 'The tag you selected does not exist in our system. Please consider submitting this tag.'

	else:
		msg_html = ""
		tag = bytags.keys()[0]
		post_ids = bytags[tag]
		msg_html += '<b>TAG - ' + tag + ':</b>'
		

	if author or tag:
		posts_html += '<h4>Posts</h4><ul>'
		for post_id in post_ids:
			title = unistr_to_html(posts[post_id][0])
			author = unistr_to_html(posts[post_id][2])
			posts_html += '<li><a href=%s>%s</a> by %s</li>' % (posts[post_id][1], title, author)
		posts_html += '</ul>'

	feeds_html = []
	for line in open('feedlist.txt').readlines():
		line = line.strip('\n')
		feed_attrs = line.split('\t')
		feeds_html.append('<li>%s - <a href=%s>%s</a></li>' % (feed_attrs[0], feed_attrs[-1], feed_attrs[-1]))
	feeds_html.sort()
	feeds_html = ''.join(feeds_html)
	
	synonyms_html = []
	for line in codecs.open('synonyms.txt', encoding='utf-8').readlines():
		line = line.strip('\n')
		syn_attrs = line.split('\t')
		synonyms_html.append('<li>%s - %s</li>' % (unistr_to_html(syn_attrs[0]), unistr_to_html(syn_attrs[-1])))
	synonyms_html.sort()
	synonyms_html = ''.join(synonyms_html)

	reply = reply % (refresh_time, tags_html, author_html, msg_html, posts_html, feeds_html, synonyms_html)
	print reply
